<?php

namespace App\Http\Controllers;

use App\Models\PluginCounter;
use App\Models\PluginCounterRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CounterController
{
    /**
     * 获取计数记录
     *
     * @param Request $request
     */
    public function record(Request $request)
    {
        $request->validate([
            'access_key' => 'required|string|regex:/^[A-Za-z0-9]+$/|min:6|max:32',
            'account' => 'required|string|alpha_num|min:6|max:32',
            'page' => 'integer|min:1',
            'size' => 'integer|min:1|max:100'
        ]);
        $accessKey = $request->post('access_key');
        $account = $request->post('account');
        $page = $request->post('page', 1);
        $size = $request->post('size', 10);
        $counterId=PluginCounter::where('access_key', $accessKey)
            ->where('account', $account)
            ->value('id');
        if (!$counterId) {
            return response()->json(['message' => '账号不存在'], 404);
        }
        $records=PluginCounterRecord::where('plugin_counter_id',$counterId)->skip(($page-1)*$size)->take($size)
            ->orderBy('created_at', 'desc')
            ->get(['amount', 'created_at']);
        return response()->json([
            'message' => '记录查询成功',
            'data' => $records,
            'page' => $page,
            'size' => $size,
            'total' => PluginCounterRecord::where('plugin_counter_id', $counterId)->count()
        ], 200);
    }
    /**
     * 增加计数
     *
     * @param Request $request
     */
    public function increase(Request $request)
    {
        $request->validate([
            'access_key' => 'required|string|regex:/^[A-Za-z0-9]+$/|min:6|max:32',
            'account' => 'required|string|alpha_num|min:6|max:32',
            'count' => 'required|integer'
        ]);
        $accessKey = $request->post('access_key');
        $account = $request->post('account');
        $count = $request->post('count');
        try{
            DB::beginTransaction();
            $counter=PluginCounter::where('access_key',$accessKey)->where('account',$account)->first();
            if (!$counter) {
                $counter = PluginCounter::create([
                    'access_key' => $accessKey,
                    'account' => $account,
                    'count' => $count,
                    'status' => 1
                ]);
            }else{
                $counter->count += $count;
                $counter->save();
            }
            $counterId= $counter->id;
            PluginCounterRecord::create([
                'plugin_counter_id' => $counterId,
                'amount' => $count,
            ]);
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => '计数增加失败: ' . $e->getMessage()], 500);
        }
        return response()->json(['message' => '计数增加成功', 'data' => $counter->count], 200);
    }
}
